import { memo, useState, useEffect } from "react"
import { TreeSelect } from "antd"

import { postJson } from '@/utils/http/linitly.request.js'

const DeptTreeSelect = ({
  value,
  onChange,
  // 是否显示顶级的空部门信息，默认为true
  showTopNull = true
}) => {

  const [ depts, setDepts ] = useState([])

  useEffect(() => {
    getDepts()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <TreeSelect treeDefaultExpandAll={true} value={value} placeholder="请选择" treeLine={true} treeData={depts} onSelect={onSelect} />
  )

  function getDepts() {
    postJson('/sysDept/findAllSelect')
    .then((res) => {
      const treeDatas = getTreeSelectData(res)
      const depts = showTopNull ? [{title: '无', value: 0}, ...treeDatas] : treeDatas
      setDepts(depts)
    })
  }

  function getTreeSelectData(datas) {
    return datas.map(value => {
      return value.children && value.children.length > 0
      ?
      {
        title: value.name,
        value: value.id,
        children: getTreeSelectData(value.children)
      }
      :
      {
        title: value.name,
        value: value.id
      }
    })
  }

  function onSelect(value) {
    onChange(value)
  }
}


export default memo(DeptTreeSelect)
